using System.Web.UI;
using Microsoft.SharePoint.WebPartPages;

namespace WebPartZoneAdapter
{
    /// <summary>
    /// ControlAdapter for "Microsoft.SharePoint.WebPartPages.WebPartZone"
    /// Last edited: 20080329 by S. Schutten, Macaw
    /// 
    /// By using this ControlAdapter for the WebPartZone, the rendered output
    /// in displaymode will be tableless and unwrapped (no wrapping divs).
    /// In AuthoringMode/EditMode the original rendering will be unaltered outputed
    /// </summary>
    /// <remarks>
    /// The Assembly of the control which this ControlAdapter binds to is placed in the GAC.
    /// That assembly should also be placed in the webapplication /bin/-folder. Otherwise a 
    /// "Could not load type" exception will be thrown
    /// </remarks>
    /// <example>
    /// In the "\App_Browsers\compat.browser" file of the webapplication add:
    ///     <browsers>
    ///         <browser refID="Default">
    /// 		    <controlAdapters>
    ///     			<adapter controlType="Microsoft.SharePoint.WebPartPages.WebPartZone"
    ///         				 adapterType="Evides.Website.Moss2007.Website.Presentation.WebPartUI.WebPartZone_Adapter, Evides.Website.Moss2007.Website.Presentation.WebPartUI , Version=1.0.0.0, Culture=neutral, PublicKeyToken=1fed9533c15552c3" />
    ///         	</controlAdapters>
    ///         </browser>
    ///     </browsers>
    /// </example>
    public class WebPartZone_Adapter : System.Web.UI.Adapters.ControlAdapter
    {
        protected override void Render(HtmlTextWriter writer)
        {
            bool inEditMode = false;

            // Get the reference to the WebPartZone-control to which this adapter is connected
            Microsoft.SharePoint.WebPartPages.WebPartZone wpz = this.Control as Microsoft.SharePoint.WebPartPages.WebPartZone;

            // Is the WebPartZone a valid reference?
            if (wpz != null)
            { // Yes!

                // Get the WebPartManager for this page
                SPWebPartManager swpm = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(wpz.Page);

                // Set the flag if WebPart Page-design is allowed
                inEditMode = swpm.GetDisplayMode().AllowPageDesign;
            }

            // Is the flag set that WebPart Page-design is allowed?
            if (!inEditMode)
            { // No
                // Render the web parts
                foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpz.WebParts)
                {
                    wp.RenderBeginTag(writer);
                    wp.RenderControl(writer);
                    wp.RenderEndTag(writer);
                }
            }
            else
            {
                // If we are editing the page --> render the web part as usual.
                base.Render(writer);
            }
        }
    }
}